package org.geektimes.web.mvc.initializer;

import java.lang.reflect.Modifier;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;

@HandlesTypes(ApplicationInitializer.class)
public class MyWebMvcServletContainerInitializer implements ServletContainerInitializer {

	@Override
	public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
		
		
		List<ApplicationInitializer> initializers = new LinkedList<ApplicationInitializer>();

		if (c != null) {
			for (Class<?> clazz : c) {
				if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers())
						&& ApplicationInitializer.class.isAssignableFrom(clazz)) {
					try {
						initializers.add((ApplicationInitializer) clazz.newInstance());
					} catch (Exception e) {
					}
				}
			}

			if (!initializers.isEmpty()) {
				initializers.sort(new Comparator<ApplicationInitializer>() {
					@Override
					public int compare(ApplicationInitializer o1, ApplicationInitializer o2) {
						return Integer.compare(o1.getOrder(), o2.getOrder());
					}
				});
				initializers.forEach(initializer -> {
					initializer.onStartup(ctx);
				});
			}
		}
		
	}

}
